package com.czmc.wifivideo.net.udp

import com.czmc.wifivideo.net.Receiver
import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.SocketTimeoutException

/**
 * @author czmc
 * @version 1.0
 * @email: chenzhiming@dkhs.com
 * @description TODO
 * @date 12/5/2018
 */

class UDPReceiver(val ip:String=Constant.HOST,val port:Int=Constant.PORT_SEND) : Receiver {
    override fun receive(): SearchResult? {
        val datagramSocket = DatagramSocket(port)
        try {
            val receivePacket = DatagramPacket(ByteArray(4), 0, 4)
            datagramSocket.soTimeout = 3000
            datagramSocket.receive(receivePacket)
            return SearchResult(receivePacket.address.hostName, data = String(receivePacket.data))
        }catch (e: SocketTimeoutException){

        }finally {
            datagramSocket.disconnect()
            datagramSocket.close()
        }
        return null
    }

}